<template>
  <div class="refunds">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold">退单管理</span>
      </div>
      <!-- 查询表单 -->
      <el-row>
        <el-col :span="24">
          <el-form inline class="query-form">
            <el-form-item label="退单编号">
              <el-input
                v-model="query.refundsId"
                placeholder="请输入退单编号"
              ></el-input>
            </el-form-item>
            <el-form-item label="退单状态">
              <el-select
                v-model="query.orderStatus"
                placeholder="请选择退单状态"
              >
                <el-option label="待处理" value="待处理"></el-option>
                <el-option label="已处理" value="已处理"></el-option>
                <el-option label="已拒绝" value="已拒绝"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="订单编号">
              <el-input
                v-model="query.orderId"
                placeholder="请输入订单编号"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <!-- 表格展示 -->
      <el-row>
        <el-col :span="24">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            class="refund-table"
          >
            <el-table-column
              prop="refundsId"
              label="退单编号"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="createdAt"
              label="退单时间"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="orderStatus"
              label="退单状态"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="orderId"
              label="订单编号"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="userId"
              label="用户编号"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="description"
              label="退单原因"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleAudit(scope.row)"
                  >审核</el-button
                >
                <el-button type="text" @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页组件 -->
      <el-row>
        <el-col :span="24">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose"
    >
      <el-form
        ref="refundForm"
        :model="refundForm"
        label-width="120px"
        class="edit-form"
      >
        <el-form-item label="退单编号">
          <el-input
            v-model="refundForm.refundsId"
            placeholder="请输入退单编号"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="退单时间" class="left-item">
          <el-date-picker
            v-model="refundForm.createdAt"
            type="datetime"
            placeholder="选择日期时间"
            :disabled="true"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="退单状态">
          <el-select
            v-model="refundForm.orderStatus"
            placeholder="请选择退单状态"
            :disabled="true"
            style="float: left"
          >
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
            <el-option label="已拒绝" value="已拒绝"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input
            v-model="refundForm.orderId"
            placeholder="请输入订单编号"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户编号">
          <el-input
            v-model="refundForm.userId"
            placeholder="请输入用户编号"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="退单原因">
          <el-input
            v-model="refundForm.description"
            placeholder="请输入退单原因"
            type="textarea"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="审核意见" v-if="dialogTitle === '审核退单'">
          <el-input
            v-model="refundForm.auditOpinion"
            placeholder="请输入审核意见"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleApprove"
          v-if="dialogTitle === '审核退单'"
          >审核通过</el-button
        >
        <el-button
          type="danger"
          @click="handleReject"
          v-if="dialogTitle === '审核退单'"
          >拒绝</el-button
        >
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  auditRefunds,
  deleteRefunds,
  refundsPageQuery,
} from "@/api/refundsApi";

export default {
  name: "AdminRefunds",
  data() {
    return {
      query: {
        refundsId: "",
        orderStatus: "",
        orderId: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: "新增退单",
      refundForm: {
        refundsId: "",
        userId: "",
        orderId: "",
        description: "",
        orderStatus: "",
        createdAt: "",
        auditOpinion: "", // 审核意见
      },
      rules: {
        auditOpinion: [
          {required: true, message: "审核意见不能为空", trigger: "blur"}
        ]
      },
      currentRefund: null
    };
  },
  methods: {
    // 获取退单列表
    fetchData() {
      const params = {
        pageRequestDto: {
          page: this.currentPage,
          size: this.pageSize,
        },
        query: {
          refundsId: this.query.refundsId,
          orderStatus: this.query.orderStatus,
          orderId: this.query.orderId,
        },
      };
      refundsPageQuery(params)
        .then((res) => {
          this.tableData = res.data.records || [];
          this.total = res.data.total || 0;
        })
        .catch((error) => {
          console.error("获取退单数据失败：", error);
          this.$message.error("获取退单数据失败");
        });
    },
    // 重置查询条件
    resetQuery() {
      this.query.refundsId = "";
      this.query.orderStatus = "";
      this.query.orderId = "";
      this.fetchData();
    },
    // 删除退单
    handleDelete(row) {
      this.$confirm(`确定要删除退单 ${row.refundsId} 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteRefunds(row.refundId)
            .then(() => {
              this.$message.success("删除成功");
              this.fetchData();
            })
            .catch((error) => {
              console.error("删除退单失败：", error);
              this.$message.error("删除退单失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 审核退单
    handleAudit(row) {
      this.dialogTitle = "审核退单";
      this.refundForm = { ...row };
      this.auditOpinion = ""; // 清空审核意见
      this.dialogVisible = true;
    },
    updateRefundStatus(refundId, status, successMessage) {
      const refund = {...this.refundForm};
      refund.orderStatus = status; // 设置新的退单状态
      refund.auditOpinion = this.refundForm.auditOpinion; // 添加审核意见

      auditRefunds(refundId, refund)
        .then(() => {
          this.$message.success(successMessage);
          this.fetchData();
        })
        .catch((error) => {
          console.error(
            `${status === "已处理" ? "审核通过" : "拒绝"}失败：`,
            error
          );
          this.$message.error(
            `${status === "已处理" ? "审核通过" : "拒绝"}失败`
          );
        });
      this.dialogVisible = false;
    },
    handleApprove() {
      this.$refs.refundForm.validate((valid) => {
        if (valid) {
          this.updateRefundStatus(this.refundForm.refundsId, "已处理", "审核通过成功");
        } else {
          this.$message.error("审核意见不能为空");
        }
      });
    },

    handleReject() {
      this.$refs.refundForm.validate((valid) => {
        if (valid) {
          this.updateRefundStatus(this.refundForm.refundsId, "已拒绝", "拒绝成功");
        } else {
          this.$message.error("审核意见不能为空");
        }
      });
    },
    // 分页大小改变
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    // 当前页改变
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();

    },
    // 关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
  mounted() {
    this.fetchData();
  },
};
</script>

<style scoped>
.refunds {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.query-form {
  margin-bottom: 20px;
}

.refund-table {
  margin-top: 20px;
}

.add-button {
  float: left; /* 将按钮置于左侧 */
}

/* 左对齐样式 */
.left-item {
  text-align: left;
}
</style>